<template>
  <div class="edit">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
    >
      <el-form-item label="属性分类">
        <el-select
          v-model="ruleForm.attribute_category_id"
          placeholder="请选择活动区域"
        >
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="item in category"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="属性名称" prop="name">
        <el-input v-model="ruleForm.name" @input="inputIdFn"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="addFn">保存</el-button>
        <el-button @click="closeFn">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
const {
  getCategoryLists,
  addAttrbute,
  getAttrInfo,
} = require("../../request/httpApi");
export default {
  data() {
    return {
      //分类数据
      category: [],
      ruleForm: {
        name: "",
      },
      rules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        region: [
          { required: true, message: "请输入属性名称", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    //获得输入框的值
    inputIdFn(e) {
      this.ruleForm.name = e;
    },
    //点击保存按钮 添加数据
    addFn() {
      if (this.ruleForm.name === "" || this.ruleForm.region === "") {
        this.$message.error("请填写完整");
        return;
      } else {
        addAttrbute({
          id: this.$route.params.aid,
          name: this.ruleForm.name,
          attribute_category_id: this.ruleForm.attribute_category_id,
        }).then((res) => {
          if (res.errno === 0) {
            this.$route.params.aid
              ? this.$message.success("属性修改成功")
              : this.$message.success("属性添加成功");
          }
          this.$router.push("/attribute");
        });
      }
    },
    //点击取消 跳回之前页面
    closeFn() {
      this.$router.go(-1);
    },
  },
  created() {
    // console.log(this.$route.params.aid);
    //分类列表的数据
    getCategoryLists().then((res) => {
      this.category = res.data;
    });
    //获取单个属性的数据

    getAttrInfo({
      id: this.$route.params.aid,
    }).then((res) => {
      console.log(res.data);
      this.ruleForm = res.data;
      //分类id
      // this.ruleForm.region = res.data.attribute_category_id
    });
  },
};
</script>

<style lang="less">
.edit {
  padding: 10px;
  background-color: #fff;
  .el-input__inner {
    width: 225px;
  }
}
</style>